package com.joe.codemother.core;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.joe.codemother.entity.enums.GenerateTypeEnum;
import com.joe.codemother.exception.BusinessException;
import com.joe.codemother.exception.ErrorCode;

import java.io.File;
import java.nio.charset.StandardCharsets;

import static com.joe.codemother.constant.FileConstant.FILE_ROOT_PATH;

public abstract class SaveFileTemplate<T> {

    ;

    public final File saveCode(T result, Long appId){
        if(!validateResult(result)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"fileGenerate failed!");
        }
        String dirPath = buildUniqueDir(appId);
        return saveFiles(result,dirPath);
    }

    protected abstract GenerateTypeEnum generateType();

    protected final String buildUniqueDir(Long appId){
        String generateType = generateType().getValue();
        String fileName = StrUtil.format("{}_{}",generateType, appId);
        String filePath = FILE_ROOT_PATH+ File.separator + fileName;
        FileUtil.mkdir(filePath);
        return filePath;
    }

    protected boolean validateResult(T result){
        if(result == null){
            return false;
        }
        return true;
    }

    protected final void saveFile(String dirPath, String fileName, String content){
        FileUtil.writeString(content, dirPath + File.separator + fileName, StandardCharsets.UTF_8);
    }

    protected abstract File saveFiles(T result, String dirPath);

}
